package org.sgy.mall.dao.impl;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.sgy.mall.dao.OrderDao;
import org.sgy.mall.dao.SuperDao;
import org.sgy.mall.model.OrderDetail;
import org.sgy.mall.model.OrderInfo;

public class OrderDaoImpl extends SuperDao implements OrderDao {

	@Override
	public boolean add(OrderInfo orderInfo) {
		try {
			// 关闭自动提交
			connection.setAutoCommit(false);
			// 1.插入订单信息
			String sql1 = "insert into order_info (username,address,order_time) values(?,?,?)";
			PreparedStatement statement = connection.prepareStatement(sql1);
			statement.setString(1, "admin");
			statement.setString(2, "苏州市工业园区");
			statement.setDate(3, new Date(orderInfo.getOrderTime().getTime()));
			int row = statement.executeUpdate();
			if (row > 0) {
				// 2 获取订单id
				String sql2 = "select id from order_info order by id desc limit 1";
				statement = connection.prepareCall(sql2);
				ResultSet result = statement.executeQuery();
				if (result.next()) {
					orderInfo.setId(result.getInt(1));
				}
				// 3.插入订单明细
				String sql3 = "insert into order_detail(order_id,product_name,price,num) values(?,?,?,?) ";
				statement = connection.prepareStatement(sql3);
				for (OrderDetail detail : orderInfo.getDetailList()) {
					statement.setInt(1, orderInfo.getId());
					statement.setString(2, detail.getProductName());
					statement.setInt(3, detail.getPrice());
					statement.setInt(4, detail.getNum());
					row = statement.executeUpdate();
					if (row <= 0) {
						connection.rollback();
						break;
					}
				}
			}
			// 提交
			connection.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
				// 异常回滚
				connection.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				// 恢复默认值
				connection.setAutoCommit(true);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	@Override
	public List<OrderInfo> list() {
		String sql = "select * from order_info order by id";
		List<OrderInfo> list = new ArrayList<OrderInfo>();
		try {
			PreparedStatement statement = connection.prepareStatement(sql);
			ResultSet rs = statement.executeQuery();
			while (rs.next()) {
				OrderInfo order = new OrderInfo();
				order.setId(rs.getInt("id"));
				order.setUserId(rs.getString("user_id"));
				order.setUsername(rs.getString("username"));
				order.setAddress(rs.getString("address"));
				order.setOrderTime(rs.getDate("order_time"));
				list.add(order);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

}
